<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\Query;
use DB;
class QueryController extends Controller
{
    protected $fields = [
        'uid' => 0,
        'name' => '',
        'query' => '',
        'phone' => '',
        'status' => '',
        'msg' => '',
		'wx'=>'',
		'domain'=>'',
		'qq'=>'',
		'email'=>'',
		'channel'=>'',
		'city'=>'',
		'title'=>'',
		'nick'=>'',
		'suffix'=>'',
		'kfwx'=>''
    ];

    public function __construct(Request $request)
    {
        /*   $this->uid = auth()->user()->id;
          $condition = [['wechats.uid', '>', 0],];
          if($this->uid > 1){
              $condition = array('wechats.uid'=>$this->uid);

          }
          $this->condition = $condition; */
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request,$gid=-1)
    {

        $uid = auth()->user()->id;
		$data = array();
        if ($request->ajax()) {
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $data['recordsTotal'] = Query::where('uid',$uid)->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Query::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('query', 'like', '%' . $search['value'] . '%')
                        ->orWhere('phone', 'like', '%' . $search['value'] . '%')
						->orWhere('wx', 'like', '%' . $search['value'] . '%');
                })->where('uid',$uid)->count();

                $data['data'] = Query::where(function ($query) use ($search) {
                        $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('query', 'like', '%' . $search['value'] . '%')
                        ->orWhere('phone', 'like', '%' . $search['value'] . '%')
						->orWhere('wx', 'like', '%' . $search['value'] . '%');
                    })
                    ->where('uid',$uid)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = Query::where('uid',$uid)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        return view('admin.query.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
       
        return view('admin.query.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      
        foreach (array_keys($this->fields) as $field) {
            $wxArr[$field] = $request->get($field);
        }
       
		event(new \App\Events\userActionEvent('\App\Models\Query',0, 1, '新增留言['.$request->name.']'));
		return redirect('/admin/query')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Query::find((int)$id);
        if (!$tag) return redirect('/admin/query')->withErrors("找不到该留言!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $tag->$field);
        }
		$data['id'] = $id;
		$data['username'] = User::where('id',$data['uid'])->value('name');
        return view('admin.query.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $tag = Query::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            if ($field == 'status') {
                $tag->$field = $request->get($field);
            }
           if ($field == 'msg') {
                $tag->$field = $request->get($field);
            }
        }
        $tag->save();
		event(new \App\Events\userActionEvent('\App\Models\Query',$id, 3, '处理留言['.$tag->name.']'));
        return redirect('/admin/query')->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = Query::find((int)$id);
            if ($tag) {
				event(new \App\Events\userActionEvent('\App\Models\Query',$id, 2, '删除留言['.$tag->name.']'));
				$tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
            $recordRows = Query::whereIn('id', $idArr)->get();
			$wx_nums = '';
            foreach($recordRows as $rr){
				$wx_nums.=$rr->name."、";
			}
			$recordRow = $recordRows->delete();
			if (!$recordRow) {
						return redirect()->back()->withErrors("删除失败");
				}
			event(new \App\Events\userActionEvent('\App\Models\Query',0, 2, '删除留言['.$wx_nums.']'));
			return redirect()->back()->withSuccess("删除成功");
		}
	}

	/*
	*留言统计
	*/
	public function chart(Request $request){
		
		$data 				= [];
		$day				= 30;
		$start_time			= date("Y-m-d H:i:s", strtotime('-'.$day.'day'));
		$end_time			= date("Y-m-d H:i:s");
		$name				= '';
		$phone				= '';
		$wx					= '';
		$kfwx				= '';
		$query				= '';
		$data['days']		= [];
		$data['counts']		= [];
		
		if ($request->isMethod('post')){
			$start_time		= $request->get('start_time');
			$end_time		= $request->get('end_time');
			$name			= $request->get('name');
			$phone			= $request->get('phone');
			$wx				= $request->get('wx');
			$kfwx			= $request->get('kfwx');
			$query			= $request->get('query');
			$second1 		= strtotime($end_time);
			$second2 		= strtotime($start_time);
			$day			= floor(($second1 - $second2) / 86400);
			
		}
		$querys 			= Query::select('id','created_at')->where('created_at','<=',$end_time)->where('created_at','>=',$start_time)
									->where('uid',auth()->user()->id)
									->where(function($q)use($name){
										if($name!=''){
											$q->where('name','like','%'.$name.'%');
										}
									})
									->where(function($q)use($phone){
										if($phone!=''){
											$q->where('phone','like','%'.$phone.'%');
										}
									})
									->where(function($q)use($wx){
										if($wx!=''){
											$q->where('wx','like','%'.$wx.'%');
										}
									})
									->where(function($q)use($query){
										if($query!=''){
											$q->where('query','like','%'.$query.'%');
										}
									})
									->where(function($q)use($kfwx){
										if($kfwx!=''){
											$q->where('kfwx','like','%'.$kfwx.'%');
										}
									})
									->get()->toArray();
		for($i=0;$i<=$day;$i++){
			$today 			= date("Y-m-d",strtotime($start_time)+86400*$i);//date("Y-m-d", strtotime(' -'. $i . 'day'));
			$data['days'][]	= date("m-d",strtotime($start_time)+86400*$i);
			$count			= 0;
			foreach($querys as $query){ 
				if(date('Y-m-d',strtotime($query['created_at'])) == $today){
					++$count;
				}
			}
			$data['counts'][]=$count;
		}
		$data['name']		= $name;
		$data['phone']		= $phone;
		$data['wx']			= $wx;
		$data['query']		= $query;
		$data['kfwx']		= $kfwx;
		$data['start_time']	= $start_time;
		$data['end_time']	= $end_time;
		return view('admin.query.chart',$data);
	}
	//表格统计模式
	public function table(Request $request){

		// 导入SMSTB
    	if($request->get('op') === 'import_smsend_tb'){
    		$res = Query::select('name','phone','channel','domain','created_at')->get();
    		$smsArr = array();
    		$nowTime = date('Y-m-d H:i:s',time());
	    		foreach ($res as $key => $obj) {
	    			$item = array();
	    			$item['name'] = $obj->name;
	    			$item['phone'] = $obj->phone;
	    			$item['channel'] = $obj->channel;
	    			$item['domain'] = $obj->domain;
	    			$item['created_at'] = date('Y-m-d H:i:s',strtotime($obj->created_at));
	    			$item['updated_at'] = $nowTime;

	    			$id = DB::table('smsends')->where('phone',$item['phone'])->value('id');
	    			if(!$id){
	    				$smsArr[] = $item;
	    			}
	    			if($key % 300 == 0){
	    				DB::table('smsends')->insert($smsArr);
	    				$smsArr =  array();
	    			}
	    			
	    			// echo $key . '-';
	    		}
    		
	    		if(count($smsArr)){
	    				DB::table('smsends')->insert($smsArr);
	    				$smsArr =  array();
	    		}
    		//
    		return redirect()->back()->withSuccess("归档分类完成Finish！");
    		exit();
    	}

		// 执行计划
    	if($request->get('op') === 'do_plan_send'){
    		$objTb = DB::table('smsends');
    		$sumToSend = $objTb->select('id')->where('status',0)->whereBetween('created_at',['2017-7-10','2017-7-11'])->count();
    		
    		$obj = $objTb->select('id','name','phone','kfwx','status')->where('status',0)->whereBetween('created_at',['2017-7-10','2017-7-11'])->first();
    	
    		$nowTime = date('Y-m-d H:i:s',time());

    		if($sumToSend){
    			echo "还有：".($sumToSend - 1) ."个计划没有执行！</br>";
	    		$sTime = mt_rand(3,10);
	    		header("Refresh: ".$sTime);
	    		echo $sTime."秒后继续执行！";
	    		//发送短信
				if($obj->id){
					//产品瘦身计划
				    $smsTmpId = 193601;
				    $mobile = config('app.debug') ? "13265113113" :$obj->phone;
                    $smsResStr = sendSMS($mobile,array($obj->name,'http://ljh.lvtop8.com/s/?wx='.$obj->kfwx.'-'.$obj->id),$smsTmpId);
                    echo $smsResStr ;
                    if(strstr(strtolower($smsResStr),'success')){
                    	// Send success
                    	$res = $objTb->where('id',$obj->id)->update(['status' => 1]);
                    }else{
                    	//参数解析失败
                    	$res = $objTb->where('id',$obj->id)->update(['status' => 3]);
                    }

					// $res = $objTb->where('id',$obj->id)->update(['status' => 1]);
				}
    		//
    		}else{
    			echo "所有计划已成功执行！";
    		}
    		exit();
    	}



		$uid 		= auth()->user()->id;
		$data 		= array();
		//$data['t']		= isset($_GET['t'])?$_GET['t']:0;
		$data['url']	= '/admin/table?v=1';
		$data['domain'] = '';
		$data['t']		= '';
		$data['tongji'] = '域名';
		$domain = 'domain';
		if(isset($_GET['domain'])){
			$domain 			= $_GET['domain'];
			$data['domain']		= '&domain='.$domain;
			switch($domain){
				case 'name':
					$data['tongji'] = '姓名';
					break;
				case 'phone':
					$data['tongji'] = '手机';
					break;
				case 'query':
					$data['tongji'] = '留言';
					break;
				case 'qq':
					$data['tongji'] = 'QQ';
					break;
				case 'email':
					$data['tongji'] = 'email';
					break;
				case 'channel':
					$data['tongji'] = '渠道';
					break;
				case 'city':
					$data['tongji'] = '城市';
					break;
				case 'title':
					$data['tongji'] = '网页标题';
					break;
				case 'nick':
					$data['tongji'] = '昵称';
					break;
				case 'suffix':
					$data['tongji'] = '网址目录';
					break;
				case 'kfwx':
					$data['tongji'] = '客服微信';
					break;
				case 'ip':
					$data['tongji'] = 'ip';
					break;
			}
		}
		if(isset($_GET['t'])){
				$data['t']			= '&t='.$_GET['t'];
			}
        if ($request->ajax()) {
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $data['recordsTotal'] = Query::where('uid',$uid)->count();
			if(isset($_GET['t'])){
				if($_GET['t']=='today'){
					$start_time 		= date('Y-m-d H:i:s',strtotime(date('Y-m-d', time())));
				}else{
					$start_time 		= date('Y-m-d H:i:s', strtotime("-".(int)$_GET['t']." minutes"));
				}
				$end_time			= date('Y-m-d H:i:s');
				$querys = Query::where('uid',$uid)->where('created_at',">",$start_time)->where('created_at',"<=",$end_time)->get();
			}else{
				 $querys = Query::where('uid',$uid)->get();
			}
			$data_arr2 					= [];
			$data_count 				= [];
			foreach($querys as $query){
				if(!isset($data_arr2[$query->$domain])){
					$data_arr2[$query->$domain] = [];//创建行
				}
				foreach (array_keys($this->fields) as $field) {
					if(!isset($data_arr2[$query->$domain][$field."_count"])){
						$data_arr2[$query->$domain][$field."_count"] = 0;//创建列
					}
					if(!isset($data_count[$field."_count"])){
						$data_count[$field."_count"] = 0;//创建该列的总数
					}
					if($query->$field!=null){
						$data_arr2[$query->$domain][$field."_count"] = $data_arr2[$query->$domain][$field."_count"]+1;
						$data_count[$field."_count"] = $data_count[$field."_count"]+1;
					}
				}
			}
			$data_arr 					= [];
			$data_arr3 					= [];
			foreach($data_arr2 as $da2k=>$da2){
				$data_arr['domain'] = $da2k;
				foreach (array_keys($this->fields) as $field){
					$data_arr[$field."_count"] = $da2[$field."_count"];
					if($data_count[$field."_count"]!=0){
						$data_arr[$field."_bfb"] = round($da2[$field."_count"]/$data_count[$field."_count"],4)*100;
					}else{
						$data_arr[$field."_bfb"] = 0;
					}
				}
				$data_arr3[] 			= $data_arr;
			}
			
			$data_arr4 					= [];
			foreach($data_arr3 as $da3k=>$da3){
				if($da3k>=$start&&$da3k<$start+$length)
				$data_arr4[] 			= $da3;
			}
			$data['data']				= json_decode(json_encode($data_arr4));
			$data['recordsFiltered'] 	= count(json_decode(json_encode($data_arr3)));
            return response()->json($data);
        }
		return view('admin.query.table',$data);
	}
}



























